package db

import (
	"fmt"
	"project/PersonalBlog/model"
)

//InsertArticle ..插入文章
func InsertArticle(article *model.ArticleDetail) (id int64) {
	var err error
	//category_id,content,title,view_count,comment_count,username,summary
	res, err := Stmt[StmtInsertArticle].Exec(article.ArticleInfo.CategoryID, article.Content, article.Title, article.ViewCount, article.CommentCount, article.UserName, article.Summary)
	if err != nil {
		return -1
	}
	id, err = res.LastInsertId()
	return id
}

//GetArticle ..拉取一片文章详情
func GetArticle(id int64) (article *model.ArticleDetail) {
	article = &model.ArticleDetail{}
	article.ID = id
	//category_id,title,view_count,comment_count,username,summary,create_time,content
	err := Stmt[StmtGetArticle].QueryRow(id).Scan(&article.ArticleInfo.CategoryID, &article.Title, &article.ViewCount, &article.CommentCount, &article.UserName, &article.Summary, &article.CreateTime, &article.Content)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return
}

//GetArticleList ..拉取文章列表
func GetArticleList(pageid int64) (articlelist []*model.ArticleInfo) {
	rows, err := Stmt[StmtGetPageArticle].Query(pageid, 20)
	if err != nil {
		fmt.Println(err.Error())
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		article := &model.ArticleInfo{}
		//ID,category_id,title,view_count,comment_count,username,summary,create_time
		err := rows.Scan(&article.ID, &article.CategoryID, &article.Title, &article.ViewCount, &article.CommentCount, &article.UserName, &article.Summary, &article.CreateTime)
		if err != nil {
			fmt.Println(err.Error())
			continue
		}
		articlelist = append(articlelist, article)
	}
	return
}

//GetSimilarArticles ..拉取同类文章列表
func GetSimilarArticles(id int32) (articlelist []*model.ArticleInfo) {
	rows, err := Stmt[StmtGetSimilarArticles].Query(id, 20)
	if err != nil {
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		article := &model.ArticleInfo{}
		//ID,category_id,title,view_count,comment_count,username,summary,create_time
		err := rows.Scan(&article.ID, &article.CategoryID, &article.Title, &article.ViewCount, &article.CommentCount, &article.UserName, &article.Summary, &article.CreateTime)
		if err != nil {
			continue
		}
		articlelist = append(articlelist, article)
	}
	return
}
